
#include "Common.h"
#include "ByteBuffer.h"
#include "WorldPacket.h"
#include "UpdateData.h"
#include "Log.h"
#include "Opcodes.h"
#include "World.h"
#include "zlib.h"

UpdateData::UpdateData() : m_blockCount(0) { }

void UpdateData::AddOutOfRangeGUID(std::set<ObjectGuid>& guids)
{
    m_outOfRangeGUIDs.insert(guids.begin(),guids.end());
}

void UpdateData::AddOutOfRangeGUID(const ObjectGuid &guid)
{
    m_outOfRangeGUIDs.insert(guid);
}

void UpdateData::AddUpdateBlock(const ByteBuffer &block)
{
    m_data.append(block);
    ++m_blockCount;
}

void UpdateData::Compress(void* dst, uint32 *dst_size, void* src, int src_size)
{
    z_stream c_stream;

    c_stream.zalloc = (alloc_func)nullptr;
    c_stream.zfree = (free_func)nullptr;
    c_stream.opaque = (voidpf)nullptr;

    // default Z_BEST_SPEED (1)
    int z_res = deflateInit(&c_stream, sWorld->getConfig(CONFIG_COMPRESSION));
    if (z_res != Z_OK)
    {
        TC_LOG_ERROR("misc","Can't compress update packet (zlib: deflateInit) Error code: %i (%s)",z_res,zError(z_res));
        *dst_size = 0;
        return;
    }

    c_stream.next_out = (Bytef*)dst;
    c_stream.avail_out = *dst_size;
    c_stream.next_in = (Bytef*)src;
    c_stream.avail_in = (uInt)src_size;

    z_res = deflate(&c_stream, Z_NO_FLUSH);
    if (z_res != Z_OK)
    {
        TC_LOG_ERROR("misc","Can't compress update packet (zlib: deflate) Error code: %i (%s)",z_res,zError(z_res));
        *dst_size = 0;
        return;
    }

    if (c_stream.avail_in != 0)
    {
        TC_LOG_ERROR("misc","Can't compress update packet (zlib: deflate not greedy)");
        *dst_size = 0;
        return;
    }

    z_res = deflate(&c_stream, Z_FINISH);
    if (z_res != Z_STREAM_END)
    {
        TC_LOG_ERROR("misc","Can't compress update packet (zlib: deflate should report Z_STREAM_END instead %i (%s)",z_res,zError(z_res));
        *dst_size = 0;
        return;
    }

    z_res = deflateEnd(&c_stream);
    if (z_res != Z_OK)
    {
        TC_LOG_ERROR("misc","Can't compress update packet (zlib: deflateEnd) Error code: %i (%s)",z_res,zError(z_res));
        *dst_size = 0;
        return;
    }

    *dst_size = c_stream.total_out;
}

bool UpdateData::BuildPacket(WorldPacket *packet, bool hasTransport)
{
    ByteBuffer buf(m_data.size() + 10 + m_outOfRangeGUIDs.size()*9);

    buf << (uint32) (!m_outOfRangeGUIDs.empty() ? m_blockCount + 1 : m_blockCount);
#ifndef LICH_KING
    buf << (uint8) (hasTransport ? true : false);
#endif

    if(!m_outOfRangeGUIDs.empty())
    {
        buf << (uint8) UPDATETYPE_OUT_OF_RANGE_OBJECTS;
        buf << (uint32) m_outOfRangeGUIDs.size();

        for (auto i : m_outOfRangeGUIDs)
            buf << PackedGuid(i);
    }

    buf.append(m_data);

    size_t pSize = buf.wpos();                              // use real used data size

    if (m_data.size() > 100 )
    {
        uint32 destsize = compressBound(pSize);
        packet->resize(destsize + sizeof(uint32));

        packet->put(0, (uint32)buf.size());
        Compress(const_cast<uint8*>(packet->contents()) + sizeof(uint32), &destsize, (void*)buf.contents(), pSize);
        if (destsize == 0)
            return false;

        packet->resize( destsize + sizeof(uint32) );
        packet->SetOpcode( SMSG_COMPRESSED_UPDATE_OBJECT );
    }
    else
    {
        packet->append(buf);
        packet->SetOpcode( SMSG_UPDATE_OBJECT );
    }

    return true;
}

void UpdateData::Clear()
{
    m_data.clear();
    m_outOfRangeGUIDs.clear();
    m_blockCount = 0;
}

